package org.lee.openoffice.service.impl;

import org.lee.openoffice.service.IConvertService;
import org.lee.openoffice.util.FileUtils;
import org.lee.openoffice.util.StreamUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@Service
public class ConvertService implements IConvertService {
    @Override
    public void preview(String url, HttpServletResponse response) throws Exception {
        String ext = FileUtils.getExt(url);
        String[] types = {"txt", "doc", "docx", "xls", "xlsx", "ppt", "pptx"};
        List<String> supportTypes = CollectionUtils.arrayToList(types);
        if (!supportTypes.contains(ext)) {
            throw new Exception("not support format");
        }
        InputStream is = StreamUtil.fromNetFile(url, ext);
        try (OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int n;
            while ((n = is.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
            out.flush();
            is.close();
        }
    }
}
